<?php
if (!defined('__TYPECHO_ROOT_DIR__')) exit;
/** 
 * 统计网站所有访问者的IP等信息
 *      
 * @package Visits
 * @author Jamiexu
 * @version 1.0
 * @link https://blog.jamiexu.cn
 */

class Visits_Plugin implements Typecho_Plugin_Interface
{
    public static $db;
    public static $prefix;

    public static function activate()
    {
        self::$db = Typecho_Db::get();
        self::$prefix = self::$db->getPrefix();
        self::installDB();
        Helper::addPanel(3,'Visits/manage-vists.php',"访问者管理","管理访问的用户",'administrator');
    }

    public static function deactivate()
    {
        Helper::removePanel(3,'Visits/manage-vists.php');
    }

    public static function config(Typecho_Widget_Helper_Form $form)
    {
    }

    public static function personalConfig(Typecho_Widget_Helper_Form $form)
    {
    }

    public static function installDB()
    {
        $sql = "CREATE TABLE IF NOT EXISTS `" . self::$prefix . "visits`  (
            `id` int(255) UNSIGNED NOT NULL AUTO_INCREMENT,
            `ip` varchar(255) NOT NULL,
            `time` varchar(255) NOT NULL,
            `location` varchar(255) NOT NULL,
            `page` varchar(255) NOT NULL,
            PRIMARY KEY (`id`)
          )ENGINE=MyISAM DEFAULT CHARSET=utf8;";
        self::$db->query($sql, Typecho_Db::WRITE);
    }


    
    public static function render()
    {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        if (!$ip)
            $ip = $_SERVER['REMOTE_ADDR'];
        $time = strval(time());
        $location = self::getIPLocation($ip);
        $page = self::get_http_type() . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . '?' . $_SERVER['QUERY_STRING'];
        self::insertData($ip, date('Y年m月d日_H:m:i',$time), $location, $page);
    }

    public static function getIPLocation($ip)
    {
        $body = file_get_contents("http://whois.pconline.com.cn/ip.jsp?ip=$ip");
        return iconv('gb2312', 'utf-8', $body);
    }

    public static function get_http_type()
    {
        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
        return $http_type;
    }

    public static function insertData($ip, $time, $locaion, $page)
    {
        $db = Typecho_Db::get();
        $prefix = $db->getPrefix();
        $data = [];
        $data['ip'] = $ip;
        $data['time'] = $time;
        $data['location'] = $locaion;
        $data['page'] = $page;
        $db->query($db->insert($prefix . 'visits')->rows($data));
    }
}
